import React, { useEffect, useState } from 'react';
import {
  WingBlank, Button, WhiteSpace, ImagePicker,
} from 'antd-mobile';
import styles from './pic.module.css';
import { uploadNative, uploadNormal } from '../../api/file';
import { getServerUrl } from '../../utils';

const serverUrl = getServerUrl();
function Pic() {
  const initPics: Array<string> = [];
  const [pics, setPics] = useState(initPics);
  const selAlbum = () => {
    window.HWH5.chooseImage({
      flag: 1,
      imagePickerMode: 'All',
      maxSelectedCount: 12,
      showOrigin: false,
      btntxtEN: 'Done',
      btntxtCN: '完成',
      cameraFacing: 0,
      compress: '0.25',
    })
      .then(async (res) => {
        console.log('选择照片结果', res);
        const { data } = await uploadNative(res[0], (ret: any) => {
          console.log('上传中', ret);
        });
        console.log('结束上传', data);
        console.log('pics', pics);
        const retPic = data.paths.map((path: string) => serverUrl + path);
        setPics([...pics, ...retPic]);
        console.log('设置完pics', pics);
      })
      .catch((error) => {
        console.error('访问相册异常', error);
      });
  };
  const takePhoto = () => {
    window.HWH5.chooseImage({
      flag: 2,
      showShadow: '0',
    })
      .then((data) => {
        pics.concat(data);
        setPics(pics);
        console.log('拍照结果:', data);
      })
      .catch((error) => {
        console.error('拍照异常', error);
      });
  };
  const selImgChange = async (files: any) => {
    console.log(files);
    const { data } = await uploadNormal(files[0].file);
    console.log(data.paths);
  };
  return (
    <WingBlank>
      <div className={styles.picWrap}>
        {pics.map((pic, index) => (
          <img className={styles.img} src={pic} alt={`图片${index}`} />
        ))}
        <ImagePicker
          files={pics}
          onChange={selImgChange}
          multiple={false}
        />
        <Button type="primary" onClick={selAlbum}>
          选择相册
        </Button>
        <WhiteSpace />
        <Button type="primary" onClick={takePhoto}>
          拍照
        </Button>
      </div>
      <WhiteSpace />
    </WingBlank>
  );
}
export default Pic;
